import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class Leetcode107 {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        if (root==null){
            return new ArrayList<>();
        }
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        List<List<Integer>> result = new ArrayList<>();
        while (!queue.isEmpty()){
            int size = queue.size();
            ArrayList<Integer> tempList = new ArrayList<>();
            while (size>0){
                TreeNode temp = queue.pop();
                tempList.add(temp.val);
                if (temp.left!=null) queue.add(temp.left);
                if (temp.right!=null) queue.add(temp.right);
                size--;
            }
            result.add(tempList);
        }
        List<List<Integer>> res = new ArrayList<>(result.size());
        for (int i = result.size()-1; i >= 0; i--) {
            res.add(result.get(i));
        }
        return res;
    }
}
